import { Input, Modal } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
// 引入useSelector用于读取redux store中保存的数据, 引入useDispath用于分发数据
const { TextArea } = Input;

interface Props {
  modalVisible?: boolean;
  textContent?: string;
  onChange: (value: string) => void;
}

// props 传递过来的是发送消息的函数和UE4中文本编辑框已有的内容textContent
const InputModal: React.FC<Props> = (props) => {
  const { modalVisible, textContent, onChange } = props;
  const [inputModalVisible, setInputModalVisible] = useState(false);

  const inputRef = useRef(null);
  // 在state中保存目前输入框内的内容, 初始化为空字符串
  const [textValue, setTextValue] = useState('');

  const handleOk = () => {
    // 将modal对话框关闭
    setInputModalVisible(false);
    // 发送消息
    // 去除前后多余的空格
    let res = textValue.trim();
    onChange(res);
  };

  // 取消发送消息
  const handleCancel = () => {
    // 将modal对话框关闭
    setInputModalVisible(false);
    // 去除前后多余的空格
    let res = textValue.trim();
    onChange(res);
  };

  const handleChange = (e: any) => {
    // 当输入框内容发生变化时, 同步给textValue
    setTextValue(e.target.value);
  };

  useEffect(() => {
    if (modalVisible) {
      setInputModalVisible(modalVisible);
    }
  }, [modalVisible]);

  return (
    <>
      {inputModalVisible ? (
        <>
          <Modal
            centered
            closable={false}
            destroyOnClose
            title={null}
            visible={inputModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <TextArea
              showCount
              allowClear
              placeholder="请输入内容"
              defaultValue={textContent}
              ref={inputRef}
              onChange={handleChange}
            />
          </Modal>
        </>
      ) : null}
    </>
  );
};

export default InputModal;
